﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Timers;

namespace WebMvc.hub
{
    public class MyHub1 : Hub
    {
        public static Timer timer= new Timer(10000);
        public MyHub1() {
            //定时器
            timer = new Timer(10000);
            timer.AutoReset = false;
            timer.Enabled = true;
            timer.Elapsed += new ElapsedEventHandler((s, e) => Timer_Elapsed(s, e));
            timer.Start();
        }
         
        public void Hello()
        { 
            Clients.All.hello();
        }

        private void Timer_Elapsed(object s, ElapsedEventArgs e)
        {
            foreach (var item in Core.CacheOnlineUsers.OnlineUsersDictionary)
            {
                if ( Clients.Client(item.Key).GetState().Result == null)
                {
                    //说明已经不在线了
                    WebMvc.Core.CacheOnlineUsers.OnlineUsersDictionary.Remove(Context.ConnectionId);
                }
            }
        }

        public override Task OnConnected()
        {
            
            WebMvc.Core.CacheOnlineUsers. OnlineUsersDictionary.Add(Context.ConnectionId,DateTime.Now.ToString());
            return base.OnConnected();
        }
        public override Task OnReconnected()
        {
            WebMvc.Core.CacheOnlineUsers.OnlineUsersDictionary.Remove(Context.ConnectionId);

            WebMvc.Core.CacheOnlineUsers.OnlineUsersDictionary.Add(Context.ConnectionId, DateTime.Now.ToString());
            return base.OnReconnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {
            WebMvc.Core.CacheOnlineUsers.OnlineUsersDictionary.Remove(Context.ConnectionId);
            return base.OnDisconnected(stopCalled);
        }
    }
}